﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.EFDBFirst;
using YiYiTong.Rocket.Business.Biz;

namespace YiYiTong.Rocket.Api.Biz
{
    public class OrderService : ApiService
    {
        #region 交易商品订单
        /// <summary>
        /// 提交订单
        /// </summary>
        public void Build(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            CreateOrderReq model = JsonHelper.Deserialize<CreateOrderReq>(data);
            if (model.addressid <= 0 || model.goodlist.Count == 0 || model.total_money <= 0 || model.invoice_id < 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.CreateOrder(apiContext.CurrUserId, 0, model);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = result.Item2;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item3;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 支付订单
        /// </summary>
        /// <param name="apiContext"></param>
        public void Pay(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            string paypwd = dic.GetValue<string>("paypwd");
            int pay_type = dic.GetValue<int>("pay_type", -1);       //支付方式 2 余额 3 支付宝 4 微信
            decimal amt = dic.GetValue<decimal>("amt", 0);
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "订单号为空";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            if (amt <= 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "支付金额错误";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            if (!(pay_type >= 2 && EnumHelper.IsDefined<PayType>(pay_type)))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "支付方式选择错误";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            if (pay_type == (int)PayType.Balance && string.IsNullOrEmpty(paypwd))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "请输入支付密码";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.PayOrder(apiContext.CurrUserId, paypwd, order_no, amt, pay_type);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = result.Item2;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item3;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 交易订单详情
        /// </summary>
        public void GetOrder(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.GetOrder(order_no);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(result.Item2);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "订单详情为空";
            }
            apiContext.apiHttpResp = apiResponse;
        }


        /// <summary>
        /// 订单是否含税
        /// </summary>
        public void GetOrderIncludeTax(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            int include_tax = 0;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var order_info = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_NO == order_no);
            var include_tax_list = (from d in dbcontext.ADZ_OrderDetails
                                    join g in dbcontext.ADZ_GoodsMaster on d.goods_id equals g.goods_id
                                    where d.order_id == order_info.order_id && g.include_tax == 1
                                    select g.include_tax
                                   ).ToList();

            if (include_tax_list != null && include_tax_list.Any())
            {
                include_tax = 1;
            }

            var result_data = new
            {
                include_tax = include_tax
            };

            apiResponse.retCode = ResultEnum.Success;
            apiResponse.data = JsonHelper.Serialize(result_data);

            apiContext.apiHttpResp = apiResponse;
        }


        /// <summary>
        /// 我的订单
        /// </summary>
        /// <param name="apiContext"></param>
        public void GetList(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            int order_status = dic.GetValue<int>("order_status", -10);
            int pageindex = dic.GetValue<int>("pageindex", 1);
            int pagerows = dic.GetValue<int>("pagerows", 10);

            var result = OrderBiz.Instance.GetOrderList(apiContext.CurrUserId, order_status, pageindex, pagerows);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(result.Item2);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "我的订单为空";
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="apiContext"></param>
        public void Cancel(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "订单号为空";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.CancelOrder(order_no);
            if (result.Item1)
                apiResponse.retCode = ResultEnum.Success;
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 确认收货
        /// </summary>
        /// <param name="apiContext"></param>
        public void Confirm(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "订单号为空";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.ConfirmOrder(order_no);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="apiContext"></param>
        public void Delete(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "订单号为空";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.DelOrder(order_no);
            if (result.Item1)
                apiResponse.retCode = ResultEnum.Success;
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 上传付款凭证
        /// </summary>
        public void UpPayImg(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            string img_data = dic.GetValue<string>("img_data");
            string filetype = dic.GetValue<string>("filetype");
            if (string.IsNullOrEmpty(order_no) || string.IsNullOrEmpty(img_data) || string.IsNullOrEmpty(filetype))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var fileTypeLists = new string[] { "png", "jpg" };
            if (!fileTypeLists.Any(b => b.Contains(filetype)))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "图片格式错误";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.UpPayImg(order_no, img_data, filetype);
            if (result.Item1)
            {
                //发送业务消息
                BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                {
                    BusinessMsgType = (int)BusinessMsgEnum.UserUploadPingzheng,
                    msg = $"上传支付凭证成功，订单号{order_no}",
                    msg_title = "上传支付凭证成功",
                    msg_url = $"/OrderMaster/OrderMasterInfo?order_no={order_no}"
                });

                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(new { pay_img_url = result.Item3 });
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 获取付款凭证
        /// </summary>
        public void LoadPayImg(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "订单号为空";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            string img_url = OrderBiz.Instance.LoadPayImg(order_no);
            if (!string.IsNullOrEmpty(img_url))
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(new { pay_img_url = img_url });
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "无付款凭证";
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 快递实时查询
        /// </summary>
        public void ExpressQuery(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "订单号为空";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.ExpressQuery(apiContext.CurrUserId, order_no);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(result.Item3);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }
        #endregion

        #region  发票资料
        /// <summary>
        /// 上传发票资料
        /// </summary>
        public void UpInvoiceImg(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            string img_data = dic.GetValue<string>("img_data");
            string filetype = dic.GetValue<string>("filetype");
            if (string.IsNullOrEmpty(order_no) || string.IsNullOrEmpty(img_data) || string.IsNullOrEmpty(filetype))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var fileTypeLists = new string[] { "png", "jpg" };
            if (!fileTypeLists.Any(b => b.Contains(filetype)))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "图片格式错误";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.UpInvoiceImg(order_no, img_data, filetype);
            if (result.Item1)
            {
                //发送业务消息
                BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                {
                    BusinessMsgType = (int)BusinessMsgEnum.UserUploadInvoice,
                    msg = $"上传发票信息成功，订单号{order_no}",
                    msg_title = "上传发票信息成功",
                    msg_url = $"/OrderMaster/OrderMasterInfo?order_no={order_no}"
                });

                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(new { invoice_img_url = result.Item3 });
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }
        /// <summary>
        /// 获取发票资料
        /// </summary>
        public void LoadInvoiceImg(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "订单号为空";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            string img_url = OrderBiz.Instance.LoadInvoiceImg(order_no);
            if (!string.IsNullOrEmpty(img_url))
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(new { invoice_img_url = img_url });
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "无发票资料";
            }
            apiContext.apiHttpResp = apiResponse;

        }
        #endregion

        #region 预定报价
        /// <summary>
        /// 预定报价
        /// </summary>
        /// <param name="apiContext"></param>
        public void PlaceBuild(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long goods_id = dic.GetValue<long>("goods_id", 0);
            //decimal goods_amount = dic.GetValue<decimal>("goods_amount", 0);
            decimal place_price = dic.GetValue<decimal>("place_price", 0);
            if (goods_id <= 0 || place_price <= 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }


            var result = OrderBiz.Instance.GoodsPlaceBuild(apiContext.CurrUserId, goods_id, place_price);
            if (result.Item1)
                apiResponse.retCode = ResultEnum.Success;
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 获取预定报价
        /// </summary>
        /// <param name="apiContext"></param>
        public void GetPlace(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long goods_id = dic.GetValue<long>("goods_id", 0);
            if (goods_id <= 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.GetGoodsPlace(apiContext.CurrUserId, goods_id);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(new { place_price = result.Item2 });
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = result.Item3;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 取消预定
        /// </summary>
        /// <param name="apiContext"></param>
        public void CancelPlace(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long seq_id = dic.GetValue<long>("seq_id", 0);
            if (seq_id <= 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.CancelGoodsPlace(seq_id);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 删除预定报价
        /// </summary>
        /// <param name="apiContext"></param>
        public void DelPlace(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long seq_id = dic.GetValue<long>("seq_id", 0);
            if (seq_id <= 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = OrderBiz.Instance.DelGoodsPlace(seq_id);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 我的预定
        /// </summary>
        /// <param name="apiContext"></param>
        public void GetPlaceList(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            int place_status = dic.GetValue<int>("place_status", -10);
            int pageindex = dic.GetValue<int>("pageindex", 1);
            int pagerows = dic.GetValue<int>("pagerows", 10);

            var result = OrderBiz.Instance.GetPlaceList(apiContext.CurrUserId, place_status, pageindex, pagerows);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(result.Item2);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "我的预定为空";
            }
            apiContext.apiHttpResp = apiResponse;
        }
        #endregion

        #region 提现订单
        public void Cash(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            decimal cash_amt = dic.GetValue<decimal>("cash_amt");
            long cash_bank_id = dic.GetValue<long>("cash_bank_id");

            var result = OrderBiz.Instance.CreateCashOrder(apiContext.CurrUserId, cash_amt, cash_bank_id);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.message = "提现申请已提交成功。";

                //发送业务消息
                BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                {
                    BusinessMsgType = (int)BusinessMsgEnum.CashApply,
                    msg = $"用户申请提现，提现金额 {cash_amt}",
                    msg_title = "用户申请提现",
                    msg_url = $""
                });

                //发送推送消息
                AddPushMsgModel paramModel = new AddPushMsgModel
                {
                    aDZ_Pushmessage = new ADZ_Pushmessage
                    {
                        MsgType = 2,
                        ReceiveType = 1,
                        MsgTitle = "提现申请成功",
                        MsgText = $"您申请提现￥{cash_amt}已提交成功，爱电子会尽快审核操作。"
                    },
                    ReceiveUids = apiContext.CurrUserId.ToString()
                };
                PushMsgBiz.Instance.AddPushMsg(paramModel);

            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item2;
            }
            apiContext.apiHttpResp = apiResponse;
        }
        #endregion 
    }
}